<template>
  <!-- 模板内容保持不变 -->
  <div class="register-wrapper">
    <div class="bg-animation"></div>

    <el-card class="register-card">
      <div class="register-header">
        <div @click="openAvatarDialog">
          <el-avatar :src="avatarUrl" :size="50" style="cursor: pointer" @click="openAvatarDialog">
            {{ form.username || 'U' }}
            <!-- 没图时显示首字母 -->
          </el-avatar>
        </div>
        <input
          ref="avatarInput"
          type="file"
          accept="imag/*"
          style="display: none"
          @change="handleAvatarChange"
        />
        <!-- <el-icon :size="40" color="#409EFF"><UserFilled /></el-icon> -->
        <h1>注册账户</h1>
        <p>创建新账户以使用系统全部功能</p>
      </div>

      <el-form
        :model="form"
        @submit.prevent="handleRegister"
        :rules="rules"
        ref="registerForm"
        class="register-form"
        label-width="80px"
      >
        <el-form-item prop="username" label="用户名" class="username-form-item">
          <el-input
            v-model="form.username"
            prefix-icon="User"
            placeholder="请输入用户名"
            size="large"
            :maxlength="16"
          />
        </el-form-item>

        <el-form-item prop="email" label="邮箱">
          <el-input
            v-model="form.email"
            type="email"
            prefix-icon="Message"
            placeholder="请输入邮箱"
            size="large"
            :maxlength="16"
          />
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input
            v-model="form.phone"
            type="phone"
            prefix-icon="Phone"
            placeholder="请输入手机号"
            size="large"
            :maxlength="11"
          />
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="form.password"
            type="password"
            prefix-icon="Lock"
            placeholder="请输入密码（8-16位，包含字母和数字）"
            size="large"
            show-password
            :maxlength="16"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            prefix-icon="Lock"
            placeholder="请再次输入密码"
            size="large"
            show-password
            :maxlength="16"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            native-type="submit"
            :loading="loading"
            style="width: 100%"
            size="large"
          >
            注册
          </el-button>
        </el-form-item>

        <div class="register-footer">
          <span>已有账号？</span>
          <el-button type="text" @click="toLogin" class="login-link"> 立即登录 </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
// 脚本内容保持不变
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { authApi, uploadApi } from '@/api'
import { ElMessage } from 'element-plus'
import { UserFilled } from '@element-plus/icons-vue'

const avatarUrl = ref('')
const avatarInput = ref(null)
const openAvatarDialog = () => {
  avatarInput.value.click()
}
const handleAvatarChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return
  try {
    const url = await uploadApi.avatar(file)
    avatarUrl.value = url
    ElMessage.success('头像上传成功')
  } catch (err) {
    ElMessage.error(err?.response?.data?.message || '上传失败')
  }
}
// const handleAvatarChane=(e)=>{
//     const file =e.target.files[0]
//     if (file){
//       const reader =new FileReader()
//       reader.onload=(event) =>{
//         avatarUrl.value=event.target.result
//       }
//       reader.readAsDataURL(file)
//     }
// }
const router = useRouter()
const form = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  avatar: '',
})

const loading = ref(false)
const registerForm = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度在 3 到 16 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
    { max: 16, message: '邮箱长度不能超过 16 个字符', trigger: 'blur' }, // 新增邮箱长度限制
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号格式有误', trigger: 'blur' }, // 修改密码长度限制
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 16, message: '密码长度在 8 到 16 个字符', trigger: 'blur' },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/,
      message: '密码必须至少8位,且包含字母和数字',
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
    { max: 16, message: '确认密码长度不能超过 16 个字符', trigger: 'blur' }, // 新增确认密码长度限制
  ],
}

const handleRegister = async () => {
  try {
    await registerForm.value.validate()
    loading.value = true

    const { confirmPassword, ...payload } = form
    payload.avatar = avatarUrl.value || ''

    await authApi.register(payload)

    ElMessage.success('注册成功，即将跳转到登录页')
    setTimeout(() => router.push('/login'), 1500)
  } catch (err) {
    if (err?.name !== 'ValidationError') {
      ElMessage.error(err?.response?.data?.message || '注册失败')
    }
  } finally {
    loading.value = false
  }
}

const toLogin = () => router.push('/login')
</script>

<style scoped>
.register-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.bg-animation {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradientBG 15s ease infinite;
  z-index: 0;
}

@keyframes gradientBG {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.register-card {
  width: 480px; /* 适当加宽卡片，容纳标签和输入框 */
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(4px);
  position: relative;
  z-index: 1;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h1 {
  margin: 15px 0 5px;
  font-size: 24px;
  color: #333;
}

.register-header p {
  color: #666;
  font-size: 14px;
}

.register-form {
  margin-top: 20px;
}

/* 核心：统一标签样式，确保输入框左对齐 */
.el-form-item {
  margin-bottom: 20px;
  /* 让表单项目里的标签、输入框等 flex 布局，方便控制对齐 */
  display: flex;
  align-items: center;
}

.el-form-item__label {
  width: 100px; /* 固定标签宽度，根据实际需求微调，比如用户名、邮箱这些标签长度适配 */
  text-align: right; /* 标签文字右对齐，这样输入框就能整齐“接着”标签排列 */
  font-size: 14px;
  color: #666;
  padding-right: 10px;
}

.register-footer {
  text-align: center;
  margin-top: 15px;
  color: #999;
  font-size: 14px;
}

.login-link {
  color: #409eff;
  padding: 0 5px;
}
/* .profile{
  width: 50px;
  height: 50px;
  border-radius: 50%;
  cursor: pointer;
} */
/* 移动端适配 */
@media (max-width: 480px) {
  .register-card {
    width: 90%;
    padding: 30px 20px;
  }

  .register-header h1 {
    font-size: 20px;
  }

  .el-form-item__label {
    width: 80px;
    padding-right: 10px;
  }
}
</style>
